from PyQt5.QtCore import Qt,QTimer
from PyQt5.QtWidgets import QWidget,QLabel,QHBoxLayout,QVBoxLayout,QToolButton,QFrame
from PyQt5.QtGui import QPalette,QColor,QImage, QPixmap,QFontMetrics
from utils.camera_work import CamareWorker

class CameraWidget(QWidget):
    callback=None
    def __init__(self):
        super().__init__()
        self.videoframe = QLabel()
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0, 0, 0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)
        self.videoframe.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.videoframe.setText("正在打开摄像头...")
        self.videoframe.setStyleSheet("QLabel { color : #ffffff;}")
        self.AutoSingleLabelFontSize(self.videoframe)
        #总布局
        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.addWidget(self.videoframe)
        self.setLayout(self.vboxlayout)
        self.camera_open()

    def __del__(self):
        try:
            self.thread.stop()
        except AttributeError:
            print("结束")

    def setCallback(self,callback):
        self.callback=callback

    def AutoSingleLabelFontSize(self,label):
        # 创建一个QFont对象
        font = label.font()
        # 计算字体大小的范围
        fm = QFontMetrics(font)
        min_size = 1
        max_size = 200
        # 二分查找适应的字体大小
        low, high = min_size, max_size
        while low <= high:
            mid = (low + high) // 2
            font.setPointSize(mid)
            fm = QFontMetrics(font)
            rect = fm.boundingRect(label.text())
            if rect.width() <= label.width():
                low = mid + 1
            else:
                high = mid - 1
        # 设置QLabel的字体
        font.setPointSize(high)
        label.setFont(font)

    def camera_open(self):
        try:
            self.thread = CamareWorker()
            self.thread.sinOut.connect(self.slotAdd)
            self.thread.start()
        except AttributeError:
            print("失败")

    def slotAdd(self, data, width, height, bytesPerLine):
        qImg = QImage(data, width, height, bytesPerLine,QImage.Format_RGB888).rgbSwapped()
        qImg = QPixmap.fromImage(qImg)
        self.videoframe.setPixmap(qImg)
        self.videoframe.setScaledContents(True)